package com.up4years.dataapi.service.shiro;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.mgt.DefaultFilterChainManager;
import org.apache.shiro.web.filter.mgt.PathMatchingFilterChainResolver;
import org.apache.shiro.web.servlet.AbstractShiroFilter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.up4years.dataapi.service.base.BaseManager;

@Service 
public class ShiroService implements ApplicationContextAware{
	
	@Autowired
	private BaseManager baseManager;
	private Properties fixRules = new Properties();
	private ApplicationContext context;
	public ShiroService(){
	 	try {
			fixRules.load(ShiroService.class.getResourceAsStream("/shiro.properties"));
		} catch (IOException e) {
	 		e.printStackTrace();
		}
	}
	public String loadFilterChainDefinitions(){
 		StringBuffer sb = new StringBuffer();
 		Iterator<Object> iterator = fixRules.keySet().iterator();
		while(iterator.hasNext()){
			String key = (String) iterator.next();
			String value = fixRules.getProperty(key);
 			sb.append(key + " = " + value +"\r\n");
 		}
		sb.append(this.getDynamicRules());
		sb.append("/**=authc\r\n");
		return sb.toString(); 
	}
	private String getDynamicRules(){
/*		Map<String,Object> parameters = new HashMap<String,Object>();
		List<Map<String,String>> list = this.baseManager.query("Role.getAllAccessRoles", parameters);
		if(list ==null || list.size()==0)return "";
		StringBuffer sb = new StringBuffer();
		for(Map<String,String> map : list){
 			String[] role_ids = map.get("role_ids").split("_");
 			String roleIds = map.get("role_ids").replace("_", ",");
  			if(role_ids.length==1){ 				
 				sb.append(map.get("url") +"=authc,roles["+roleIds+"]\r\n");
 			}else{ 				
 				sb.append(map.get("url") +"=authc,roles[\""+roleIds+"\"]\r\n");
 			}
		}
		return sb.toString();*/
		return "";
	}
 
	public void setBaseManager(BaseManager baseManager){
		this.baseManager = baseManager;
	}
	/**
	 * 重设角色权限
	 */
	public void reload(){
		ShiroFilterFactoryBean shiroFilterFactoryBean = (org.apache.shiro.spring.web.ShiroFilterFactoryBean)this.context.getBean(ShiroFilterFactoryBean.class);
	    AbstractShiroFilter shiroFilter = null;  
        try {  
            shiroFilter = (AbstractShiroFilter) shiroFilterFactoryBean.getObject();  
        } catch (Exception e) {  
            throw new RuntimeException("get ShiroFilter from shiroFilterFactoryBean error!");  
        }  
        PathMatchingFilterChainResolver filterChainResolver = (PathMatchingFilterChainResolver) shiroFilter.getFilterChainResolver();  
        DefaultFilterChainManager manager = (DefaultFilterChainManager) filterChainResolver.getFilterChainManager();  
        // 清空老的权限控制  
        manager.getFilterChains().clear();  
        shiroFilterFactoryBean.getFilterChainDefinitionMap().clear();  
        shiroFilterFactoryBean.setFilterChainDefinitions(loadFilterChainDefinitions());
		shiroFilterFactoryBean.setFilterChainDefinitions(this.loadFilterChainDefinitions());
		//重设权限
		 Map<String, String> chains = shiroFilterFactoryBean.getFilterChainDefinitionMap();  
	     for (Map.Entry<String, String> entry : chains.entrySet()) {  
	            String url = entry.getKey();  
	            String chainDefinition = entry.getValue().trim().replace(" ", "");  
	            manager.createChain(url, chainDefinition);  
	      }  
	}
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.context = applicationContext;
	}
}
